package com.ccsoft.netty.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.ScheduledFuture;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @author chanchaw
 * @create 2022-07-19 13:11
 */
public class ServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("服务器收到消息：" + msg.text());
        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间：" + LocalDateTime.now() + " " + msg.text()));

        ChannelPipeline pipeline = ctx.pipeline();
        Channel channel = pipeline.channel();
        ScheduledFuture<?> scheduledFuture = channel.eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                channel.writeAndFlush(new TextWebSocketFrame("定时7秒后发送的消息"));
            }
        }, 7, TimeUnit.SECONDS);

        scheduledFuture.addListener(new GenericFutureListener() {

            @Override
            public void operationComplete(Future future) throws Exception {
                System.out.println("定时7秒发送的消息执行完毕！");
            }
        });
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端下线了！");
        ctx.close();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端上线了！");
    }
}
